@echo off
REM Set UTF-8 encoding to handle Chinese characters properly
chcp 65001 >nul
REM Set Java tool options for consistent encoding
set JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8 -Dconsole.encoding=UTF-8 -Duser.language=zh -Duser.country=CN
echo ========================================
echo     XHS Login Service Windows App Builder
echo     Enhanced version for Playwright support
echo ========================================

REM Set variables
set APP_NAME=XHS-Login-Service
set APP_VERSION=1.0.0
set JAR_FILE_NAME=xhs-login-service-1.0.0.jar
set JAR_FILE=target\%JAR_FILE_NAME%
set OUTPUT_DIR=target\jpackage
set APP_DESCRIPTION=XHS Login Service Windows Application
set STAGING_DIR=target\staging
set RUNTIME_DIR=target\runtime
set EXTRACTED_DIR=target\extracted
set PLAYWRIGHT_DATA_DIR=data\.ms-playwright

echo.
echo Step 1: Check Java environment...
java -version
if errorlevel 1 (
    echo Error: Java not found! Please install JDK 17 or higher
    pause
    exit /b 1
)
echo Java environment check passed

echo.
echo Step 2: Clean previous builds...
if exist "%OUTPUT_DIR%" rmdir /s /q "%OUTPUT_DIR%"
if exist "%RUNTIME_DIR%" rmdir /s /q "%RUNTIME_DIR%"
if exist "%EXTRACTED_DIR%" rmdir /s /q "%EXTRACTED_DIR%"
if exist "%STAGING_DIR%" rmdir /s /q "%STAGING_DIR%"
if exist "data" rmdir /s /q "data"
mkdir "%OUTPUT_DIR%"

echo.
echo Step 3: Clean target directory...
if exist "target" (
    echo Deleting target directory...
    rmdir /s /q "target"
    echo Target directory deleted
)

echo.
echo Step 4: Build application with Maven...
call mvn clean package -DskipTests
if errorlevel 1 (
    echo Error: Maven build failed
    pause
    exit /b 1
)
echo Maven build completed successfully

echo.
echo Step 5: Check JAR file exists...
if not exist "%JAR_FILE%" (
    echo Error: JAR file not found at %JAR_FILE%
    pause
    exit /b 1
)
echo JAR file found: %JAR_FILE%

echo.
echo Step 6: Pre-install Playwright browsers...
echo Creating Playwright data directory...
mkdir "data" 2>nul
mkdir "%PLAYWRIGHT_DATA_DIR%" 2>nul

echo.
echo [Choose download mode]
echo 1. Use Chinese mirror (Recommended, faster)
echo 2. Skip pre-installation (Faster build, download on first run)
echo.
set /p DOWNLOAD_CHOICE="Please choose (1/2, press Enter for default 1): "
if "%DOWNLOAD_CHOICE%"=="" set DOWNLOAD_CHOICE=1
if "%DOWNLOAD_CHOICE%"=="2" goto SKIP_BROWSER_INSTALL

echo.
echo Using Chinese mirror for browser pre-installation...

echo Setting Playwright environment for pre-installation...
set PLAYWRIGHT_BROWSERS_PATH=%CD%\%PLAYWRIGHT_DATA_DIR%
set PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=false
set PLAYWRIGHT_DOWNLOAD_TIMEOUT=300000

REM Set Chinese mirror for faster download
echo Setting up Chinese mirror for faster download...
set PLAYWRIGHT_DOWNLOAD_HOST=https://npmmirror.com/mirrors/playwright
set PLAYWRIGHT_DOWNLOAD_FALLBACK_HOST=https://playwright.azureedge.net

echo Playwright browsers will be installed to: %PLAYWRIGHT_BROWSERS_PATH%
echo Using Chinese mirror: %PLAYWRIGHT_DOWNLOAD_HOST%
echo This should be much faster than the default download source...
echo.

REM Use Maven to download Playwright browsers with Chinese mirror
echo Downloading Playwright browsers via Maven (using Chinese mirror)...
call mvn exec:java -Dexec.mainClass="com.microsoft.playwright.CLI" -Dexec.args="install --with-deps" -DPLAYWRIGHT_BROWSERS_PATH="%PLAYWRIGHT_BROWSERS_PATH%" -DPLAYWRIGHT_DOWNLOAD_HOST="%PLAYWRIGHT_DOWNLOAD_HOST%"

REM Check if any browsers were downloaded
set BROWSERS_INSTALLED=false
if exist "%PLAYWRIGHT_DATA_DIR%\chromium*" set BROWSERS_INSTALLED=true
if exist "%PLAYWRIGHT_DATA_DIR%\webkit*" set BROWSERS_INSTALLED=true
if exist "%PLAYWRIGHT_DATA_DIR%\firefox*" set BROWSERS_INSTALLED=true

if "%BROWSERS_INSTALLED%"=="true" (
    echo SUCCESS: Playwright browsers have been pre-installed!
    echo Browser installation directory: %PLAYWRIGHT_BROWSERS_PATH%
    dir "%PLAYWRIGHT_DATA_DIR%" /b
) else (
    echo WARNING: Playwright browser pre-installation failed or incomplete
    echo Browsers will be downloaded automatically when application starts
    echo This may cause first startup to take longer
)
goto CONTINUE_BUILD

:SKIP_BROWSER_INSTALL
echo.
echo Skipping browser pre-installation, will download on first run...
echo Setting runtime auto-download environment variables...
set PLAYWRIGHT_BROWSERS_PATH=%CD%\%PLAYWRIGHT_DATA_DIR%
set PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=false

:CONTINUE_BUILD

echo.
echo Step 7: Extract Spring Boot layers for Playwright compatibility...
echo Using layertools to extract JAR for dependency analysis...
mkdir "%EXTRACTED_DIR%"

REM Store current directory
set CURRENT_DIR=%CD%

REM Change to extracted directory and use absolute path to JAR
cd "%EXTRACTED_DIR%"
java -Djarmode=layertools -jar "%CURRENT_DIR%\%JAR_FILE%" extract

REM Return to original directory
cd "%CURRENT_DIR%"

if not exist "%EXTRACTED_DIR%\dependencies" (
    echo Error: Failed to extract Spring Boot layers
    echo JAR file path: %CURRENT_DIR%\%JAR_FILE%
    echo Current directory: %CD%
    pause
    exit /b 1
)

echo Spring Boot layers extracted successfully

echo.
echo Step 8: Create staging directory...
mkdir "%STAGING_DIR%"
copy "%JAR_FILE%" "%STAGING_DIR%\"
echo JAR file copied to staging directory

echo.
echo Step 9: Check for custom JRE requirement...
set USE_CUSTOM_JRE=false

echo Checking if custom JRE with additional security modules is required...
findstr /c:"java.security.jgss" "%EXTRACTED_DIR%\*" >nul 2>&1
if not errorlevel 1 set USE_CUSTOM_JRE=true

findstr /c:"playwright" "%EXTRACTED_DIR%\*" >nul 2>&1
if not errorlevel 1 set USE_CUSTOM_JRE=true

if "%USE_CUSTOM_JRE%"=="true" (
    echo Custom JRE with security modules required for Playwright
    echo.
    echo Step 10a: Create custom JRE with security modules...
    echo Creating optimized JRE with Playwright and security support...

    jlink --module-path "%JAVA_HOME%\jmods" ^
        --add-modules java.base,java.logging,java.desktop,java.management,java.sql,java.naming,java.security.jgss,jdk.security.auth,jdk.crypto.cryptoki,java.smartcardio,jdk.security.jgss,java.xml,java.instrument,jdk.management,java.management.rmi,jdk.httpserver,java.net.http ^
        --output "%RUNTIME_DIR%" ^
        --strip-debug ^
        --no-man-pages ^
        --no-header-files ^
        --compress=2

    if errorlevel 1 (
        echo Error: Failed to create custom JRE
        echo Falling back to system JRE
        set USE_CUSTOM_JRE=false
    ) else (
        echo Custom JRE created successfully with security modules
    )
)

echo.
echo Step 10b: Create portable Windows application...
echo Creating app-image with Playwright and auto-browser-launch support...

if "%USE_CUSTOM_JRE%"=="true" (
    echo Creating portable app with custom JRE...
    jpackage ^
        --type app-image ^
        --input "%STAGING_DIR%" ^
        --name "%APP_NAME%" ^
        --main-jar "%JAR_FILE_NAME%" ^
        --runtime-image "%RUNTIME_DIR%" ^
        --dest "%OUTPUT_DIR%" ^
        --app-version "%APP_VERSION%" ^
        --win-console ^
        --java-options "-Xmx2g" ^
        --java-options "-Xms512m" ^
        --java-options "-Dserver.port=8080" ^
        --java-options "-Dfile.encoding=UTF-8" ^
        --java-options "-Dconsole.encoding=UTF-8" ^
        --java-options "-Duser.language=zh" ^
        --java-options "-Duser.country=CN" ^
        --java-options "-Djava.awt.headless=false" ^
        --java-options "-Duser.timezone=Asia/Shanghai" ^
        --java-options "-DPLAYWRIGHT_BROWSERS_PATH=data/.ms-playwright" ^
        --java-options "-Dplaywright.skip.browser.download=false" ^
        --verbose
) else (
    echo Creating portable app with system default JRE...
jpackage ^
        --type app-image ^
    --input "%STAGING_DIR%" ^
    --name "%APP_NAME%" ^
    --main-jar "%JAR_FILE_NAME%" ^
    --dest "%OUTPUT_DIR%" ^
    --app-version "%APP_VERSION%" ^
        --win-console ^
        --java-options "-Xmx2g" ^
        --java-options "-Xms512m" ^
        --java-options "-Dserver.port=8080" ^
    --java-options "-Dfile.encoding=UTF-8" ^
        --java-options "-Dconsole.encoding=UTF-8" ^
        --java-options "-Duser.language=zh" ^
        --java-options "-Duser.country=CN" ^
        --java-options "-Djava.awt.headless=false" ^
        --java-options "-Duser.timezone=Asia/Shanghai" ^
        --java-options "-DPLAYWRIGHT_BROWSERS_PATH=data/.ms-playwright" ^
        --java-options "-Dplaywright.skip.browser.download=false" ^
        --java-options "--add-opens=java.base/java.lang=ALL-UNNAMED" ^
        --java-options "--add-opens=java.base/java.util=ALL-UNNAMED" ^
        --java-options "--add-opens=java.base/java.io=ALL-UNNAMED" ^
        --java-options "--add-opens=java.base/java.net=ALL-UNNAMED" ^
        --java-options "--add-opens=java.base/java.time=ALL-UNNAMED" ^
    --verbose
)

if errorlevel 1 (
    echo.
    echo Portable application creation failed!
    echo.
    echo Possible solutions:
    echo 1. Ensure using JDK 17 or higher
    echo 2. Ensure JAVA_HOME environment variable is set correctly
    echo 3. Try running this script as administrator
    echo 4. Check disk space is sufficient
    echo 5. Check Windows Defender is not blocking file creation
    echo.
    echo Alternative options:
    echo 1. Run JAR directly: java -jar "%JAR_FILE%"
    echo 2. Use extracted layers: java -cp "%EXTRACTED_DIR%\*" org.springframework.boot.loader.launch.JarLauncher
    echo 3. Or copy JAR to desktop and double-click to run
    pause
    exit /b 1
)

echo.
echo Step 11: Copy pre-installed Playwright browsers to portable app...
mkdir "%OUTPUT_DIR%\%APP_NAME%\data" 2>nul

if "%BROWSERS_INSTALLED%"=="true" (
    echo Copying pre-installed Playwright browsers...
    xcopy "%PLAYWRIGHT_DATA_DIR%" "%OUTPUT_DIR%\%APP_NAME%\data\.ms-playwright\" /E /I /Q /S /Y

    if exist "%OUTPUT_DIR%\%APP_NAME%\data\.ms-playwright" (
        echo SUCCESS: Playwright browsers copied to portable app!
        echo Browser location: %OUTPUT_DIR%\%APP_NAME%\data\.ms-playwright\
        dir "%OUTPUT_DIR%\%APP_NAME%\data\.ms-playwright" /b
    ) else (
        echo WARNING: Failed to copy Playwright browsers to portable app
    )
) else (
    echo Creating placeholder directory for Playwright browsers...
    mkdir "%OUTPUT_DIR%\%APP_NAME%\data\.ms-playwright" 2>nul
    echo Note: Browsers will be downloaded on first application startup
)

echo.
echo ========================================
echo     Portable App Created Successfully!
echo ========================================
echo.
echo Portable app location: %OUTPUT_DIR%\%APP_NAME%
echo Executable file: %OUTPUT_DIR%\%APP_NAME%\%APP_NAME%.exe
echo.
echo PORTABLE APP FEATURES:
echo + No installation required - just double-click to run
echo + Contains embedded JRE - works on any Windows computer
echo + Can be copied to USB drive or other computers
echo + Data files stored locally with the exe
echo + Includes console window for debugging
echo + Auto-opens browser to http://localhost:8080/xhs/index.html
echo + Includes Chinese mirror support for faster startup
echo.
echo USAGE INSTRUCTIONS:
echo 1. Copy the entire folder %OUTPUT_DIR%\%APP_NAME% to any Windows computer
echo 2. Double-click %APP_NAME%.exe to start the application
echo 3. Browser will automatically open when startup is complete
echo 4. Use the web interface for XHS login automation
echo.
echo NOTE: First startup may take longer if browsers need to be downloaded
echo.
pause